﻿using System.Threading.Tasks;
using System.Linq;
using ECommon.Components;
using ECommon.IO;
using ENode.Infrastructure;
using Domain.Sections;
using Infrastructure;
using EntityFramework.Extensions;

namespace Denormalizers.Ef
{
    [Component]
    public class SectionDenormalizer : AbstractDenormalizer,
        IMessageHandler<SectionCreatedEvent>,
        IMessageHandler<SectionNameChangedEvent>
    {
        public Task<AsyncTaskResult> HandleAsync(SectionCreatedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                db.Section.Add(new Repository.EntityFramework.Forums.Section
                {
                    Id = evnt.AggregateRootId,
                    Name = evnt.Name,
                    CreatedOn = evnt.Timestamp,
                    UpdatedOn = evnt.Timestamp,
                    Version = evnt.Version
                });
                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
        public Task<AsyncTaskResult> HandleAsync(SectionNameChangedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                var m = db.Section.Where(x => x.Id == evnt.AggregateRootId && x.Version == evnt.Version - 1).SingleOrDefault();

                m.Name = evnt.Name;
                m.UpdatedOn = evnt.Timestamp;
                m.Version = evnt.Version;

                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
}
